package com.lifo.utils.common.cookie;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @author why
 * @date 2019/5/13 0013.
 */
@Slf4j
public class CookieUtil {
    public static String getCookieVal(HttpServletRequest request, String cookieName){
        Cookie[] cookies = request.getCookies();
        if(!StringUtils.isEmpty(cookies)&&cookies.length>0){
            for(Cookie cookie : cookies){
                if(cookieName.equals(cookie.getName())){
                    log.debug("获取到cookieName==>{},cookieValue==>{}",cookieName,cookie.getValue());
                    return cookie.getValue();
                }
            }
        }else{
            log.info("cookie为空，无法获取cookie值");
            return null;
        }
        return null;
    }

    /**
     * 设置cookie
     * @param name
     * @param value
     * @param path
     * @return
     */
    public static Cookie setCookie(String name, String value, String path){
        Cookie cookie = new Cookie(name, value);
        //半小时内有效
        cookie.setMaxAge(1800000);
        cookie.setPath(path);
       return cookie;
    }

}
